from django_filters import rest_framework as filters
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status

from inventory.serializers import InventorySerializer
from inventory.models import Inventory
from utils.custom_model_viewSet import CustomModelViewSet


class InventoryFilter(filters.FilterSet):
    """
    库存过滤类，用于库存列表过滤
    """
    product_name = filters.CharFilter(field_name='product__name', lookup_expr='icontains')
    product_sku = filters.CharFilter(field_name='product__sku', lookup_expr='icontains')
    warehouse_name = filters.CharFilter(field_name='warehouse__warehouse_name', lookup_expr='icontains')
    location_code = filters.CharFilter(field_name='location__location_code', lookup_expr='icontains')
    
    class Meta:
        model = Inventory
        fields = [
            'inventory_id', 'product', 'warehouse', 'location', 
            'quantity', 'available_quantity', 'reserved_quantity', 
            'lot_number', 'serial_number', 'expiry_date'
        ]


class InventoryViewSet(CustomModelViewSet):
    """
    库存视图集，提供库存的增删改查操作
    """
    queryset = Inventory.objects.filter(is_deleted=False).order_by('product', 'warehouse', 'location')
    serializer_class = InventorySerializer
    filterset_class = InventoryFilter
    search_fields = [
        'product__name', 'product__sku', 'warehouse__warehouse_name', 
        'location__location_code', 'lot_number', 'serial_number'
    ]
    ordering_fields = ['product', 'warehouse', 'location', 'create_time', 'inventory_id']
    ordering = ['product', 'warehouse', 'location']
    enable_soft_delete = True
    
    @action(detail=False, methods=['get'], url_path='summary')
    def get_inventory_summary(self, request, *args, **kwargs):
        """
        获取库存汇总信息
        
        Args:
            request: HTTP请求对象，可包含warehouse_id参数
        
        Returns:
            Response: 包含库存汇总数据的响应
        """
        warehouse_id = request.query_params.get('warehouse_id')
        
        # 构建查询
        queryset = self.get_queryset()
        if warehouse_id:
            queryset = queryset.filter(warehouse_id=warehouse_id)
        
        # 计算汇总数据
        total_items = queryset.count()
        total_quantity = sum(item.quantity for item in queryset)
        total_available = sum(item.available_quantity for item in queryset)
        total_reserved = sum(item.reserved_quantity for item in queryset)
        
        # 计算库存总价值（如果有unit_cost字段）
        total_value = sum(
            (item.unit_cost or 0) * item.quantity 
            for item in queryset if item.unit_cost is not None
        )
        
        # 获取产品种类数量
        product_count = queryset.values('product').distinct().count()
        
        summary_data = {
            'total_items': total_items,
            'total_quantity': float(total_quantity),
            'total_available': float(total_available),
            'total_reserved': float(total_reserved),
            'total_value': float(total_value),
            'product_count': product_count
        }
        
        return Response(summary_data)